use super::module_name;
use crate::config::remote_config;
use redis_util;
use redis_util::mobc_pool::{Connection, Pool, RedisError};
use std::sync::RwLock;

lazy_static::lazy_static! {
    static ref REDISPOOLINSTANCE:RwLock<Option<Pool>> = RwLock::new(None);
}

pub(super) async fn init_redis() {
    let con = remote_config::get_common_config().redis_connection.clone();

    let redis_config_obj;
    match redis_util::RedisConfig::parse(con.as_str()) {
        Ok(val) => redis_config_obj = val,
        Err(err) => {
            remote_log_util::remote_error!(
                module_name(),
                format!("parse redis config error:{:?}", err)
            )
            .await;
            panic!("{}", err)
        }
    }

    let mut writer = REDISPOOLINSTANCE.write().unwrap();
    *writer = Some(redis_util::mobc_pool::build_redis_pool(&redis_config_obj));
}

#[allow(unused)]
pub async fn redis_db() -> Result<Connection, RedisError> {
    REDISPOOLINSTANCE
        .read()
        .unwrap()
        .as_ref()
        .unwrap()
        .get()
        .await
}
